package com.ljh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljh.mapper.AdminMapper;
import com.ljh.mapper.AdminRoleMapper;
import com.ljh.pojo.Admin;
import com.ljh.pojo.AdminRole;
import com.ljh.pojo.Role;
import com.ljh.service.IAdminService;
import com.ljh.utils.AdminUtils;
import com.ljh.utils.JwtTokenUtil;
import com.ljh.utils.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lijiahao
 * @since 2021-09-01
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    /**
     * 登录之后返回token
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        //判断验证码
        String captcha =(String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code)||!captcha.equalsIgnoreCase(code))
            return  RespBean.error("验证码错误");
        //登录判断
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails==null||!passwordEncoder.matches(password,userDetails.getPassword()))
            return RespBean.error("用户名或者密码错误");
        if (!userDetails.isEnabled())
            return RespBean.error("账号被锁定，请联系管理员");

        //更新security登录用户对象principal
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",map);
    }

    /**
     * 根据用户名返回用户
     * @param name
     * @return
     */
    @Override
    public Admin getAdminByName(String name) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",name));
    }

    @Override
    public List<Role> getRoleByAdminId(Integer adminId) {
        return adminMapper.getRoleByAdminId(adminId);
    }

    /**
     * 查询操作员
     * @param keyword
     * @return
     */

    @Override
    public List<Admin> getAllAdmin(String keyword) {

        Integer adminId = AdminUtils.getAdmin().getId();
        return adminMapper.getAllAdmin(adminId,keyword);
    }

    /**
     * 更改密码
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public RespBean updatePassWord(String oldPass, String pass, Integer adminId) {
        //根据用户id查出用户
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.println("加密密码为："+encoder.encode("456"));
        System.out.println("加密密码为："+encoder.encode("456"));
        //是否和老密码匹配
        if (encoder.matches(oldPass,admin.getPassword())){
            //更改密码
            admin.setPassword(encoder.encode(pass));
            int update = adminMapper.updateById(admin);
            if (update==1){
                return RespBean.success("更改成功");
            }
        }
        return RespBean.error("更改失败");
    }

    /**
     * 更新用户头像
     * @param url
     * @param id
     * @param authentication
     * @return
     */

    @Override
    public RespBean updateUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);
        int update = adminMapper.updateById(admin);
        if (update==1){
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功",url);
        }
        return RespBean.error("更新失败");
    }

    /**
     * 更新操作员角色
     * @param id
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer id, Integer[] ids) {
        //先全部删除
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("aid",id));
        Integer integer = adminRoleMapper.updateAdminRole(id, ids);
        if (integer  == ids.length){
            return RespBean.success("更新成功");
        }
        return  RespBean.error("更新失败");
    }
}
